<style type="text/less" lang="less" scoped>
  @import url("./index.less");
</style>

<template>
  <el-container>
    <el-main class="content-main">
      <div class="ps-panel" style="height: 100%">
        <div class="ps-panel-head">
          <i class="ps-panel-head-icon iconfont icon-list"></i>
          <span class="ps-panel-head-title">列表</span>
          <span class="query">
            <el-button type="primary" size="mini" @click="add">添加源</el-button>
          </span>
        </div>

        <div class="ps-panel-body">
          <el-table :data="tableData" size="small" highlight-current-row stripe
            style="width: 100%; margin-bottom: 10px">
            <el-table-column prop="id" label="ID" width="50"></el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column prop="type" label="类型" width="150"></el-table-column>
            <el-table-column prop="driver_name" label="驱动" width="200"></el-table-column>
            <el-table-column prop="addtime" label="添加时间" width="150"></el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="edit(scope.row)">编辑</el-button>
                <el-popover style="margin-left: 10px" width="160" trigger="manual" :ref="'del_popover_' + scope.row.id">
                  <p style="text-align: center; margin: 15px 0px">
                    确定删除吗？
                  </p>
                  <div style="text-align: center; margin: 0">
                    <el-button size="mini" @click="delPopoverClose('del_popover_' + scope.row.id)">取消</el-button>
                    <el-button type="primary" size="mini" @click="del(scope.row)">确定</el-button>
                  </div>
                  <el-button type="text" slot="reference" size="small"
                    @click="delPopoverShow('del_popover_' + scope.row.id)">删除
                  </el-button>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination v-if="paginations.total > 0" :page-size="paginations.pageSize" :layout="paginations.layout"
              :total="paginations.total" :current-page="paginations.pageIndex" @current-change="jump"
              style="text-align: right">
            </el-pagination>
          </div>
        </div>
      </div>
    </el-main>

    <el-dialog :title="sourceForm.title+'数据源'" :visible.sync="sourceForm.visible" width="800px" class="edit">
      <el-form ref="sourceForm" :model="sourceForm" :rules="sourceForm.rules" label-width="100px">
        <el-form-item label="源名称：" prop="name">
          <el-input v-model="sourceForm.name" maxlength="20" placeholder="请输入源名称"></el-input>
        </el-form-item>
        <el-form-item label="源类型：" prop="type">
          <el-select v-model="sourceForm.type" placeholder="请选择" @change="exchangeType">
            <el-option v-for="item in sourceDataType" :key="item.id" :label="item.name" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="基本信息：">
          <div class="baseInfo" v-if="collectTypeValue">
            <el-form ref="formover" :model="collectBaseInfo" label-width="100px" status-icon :rules="infoRule"
              class="demo-ruleForm">
              <el-form-item v-if="
                  collectTypeValue == 'dm' ||
                  collectTypeValue == 'mysql' ||
                  collectTypeValue == 'oracle' ||
                  collectTypeValue == 'sqlserver' ||
                  collectTypeValue == 'kingbase' ||
                  collectTypeValue == 'oscar'||collectTypeValue == 'Mongodb'
                " label="主机：" prop="ip" style="height: 55px">
                <el-input v-model="collectBaseInfo.ip" size="mini" maxlength="15"></el-input>
              </el-form-item>
              <el-form-item v-if="
                  collectTypeValue == 'dm' ||
                  collectTypeValue == 'mysql' ||
                  collectTypeValue == 'oracle' ||
                  collectTypeValue == 'kingbase' ||
                  collectTypeValue == 'sqlserver' ||
                  collectTypeValue == 'oscar'||collectTypeValue == 'Mongodb'
                " label="端口：" prop="port" style="height: 55px">
                <el-input v-model="collectBaseInfo.port" size="mini"></el-input>
              </el-form-item>
              <!-- <el-form-item label="服务名：" prop="serviceName" v-if="collectTypeValue == 'oracle'" style="height: 55px">
                <el-input v-model="collectBaseInfo.serviceName" size="mini"></el-input>
              </el-form-item> -->
              <el-form-item :label="collectTypeValue == 'oracle'?'服务名：':'数据库名：'" prop="dataBaseName" v-if="
                  collectTypeValue == 'kingbase' ||
                  collectTypeValue == 'mysql' ||
                  collectTypeValue == 'oracle' ||
                  collectTypeValue == 'oscar'||collectTypeValue == 'sqlserver'||collectTypeValue == 'Mongodb'
                " style="height: 55px">
                <el-input v-model="collectBaseInfo.dataBaseName" size="mini" maxlength="50"></el-input>
              </el-form-item>
              <el-form-item label="表名称" prop="table_name" style="height: 55px" v-if="collectTypeValue == 'Mongodb'">
                <el-input v-model="collectBaseInfo.table_name" size="mini" maxlength="50"></el-input>
              </el-form-item>
              <el-form-item label="用户名：" prop="username" style="height: 55px" v-if="
                  collectTypeValue == 'dm' ||
                  collectTypeValue == 'mysql' ||
                  collectTypeValue == 'oracle' ||
                  collectTypeValue == 'sqlserver' ||
                  collectTypeValue == 'kingbase' ||
                  collectTypeValue == 'oscar'
                ">
                <el-input v-model="collectBaseInfo.username" size="mini" maxlength="50" @change="assignmentUser">
                </el-input>
              </el-form-item>
              <el-form-item label="密码：" v-if="
                  collectTypeValue == 'dm' ||
                  collectTypeValue == 'mysql' ||
                  collectTypeValue == 'oracle' ||
                  collectTypeValue == 'sqlserver' ||
                  collectTypeValue == 'kingbase' ||
                  collectTypeValue == 'oscar'
                " prop="password" style="height: 55px">
                <el-input type="password" v-model="collectBaseInfo.password" size="mini" maxlength="50"
                  @change="assignmentPass"></el-input>
              </el-form-item>
              <el-form-item label="数据库文件:"
                v-if="collectTypeValue === 'access'||collectTypeValue === 'sqlite'||collectTypeValue === 'SQLite'">
                <el-row type="flex" :gutter="1">
                  <el-col :span="19">
                    <div class="file_input">
                      <el-tag style="margin-left: 3px" placeholder="请上传示范文件" v-for="(file, index) in fileList"
                        :key="index" size="small" @close="handleClose(file)">
                        {{ file.name }}
                      </el-tag>
                    </div>
                  </el-col>
                  <el-col :span="4">
                    <el-upload ref="uploadAcc" class="upload-demo" action="#" :auto-upload="false"
                      :on-change="handleChange" :accept="available" :file-list="fileListone"
                      :http-request="changeheader" :limit="1" :show-file-list="false">
                      <el-button style="
                          background: #ccc;
                          border-radius: 1px;
                          border: none;
                          color: #333;
                          margin-top: 10px;
                        " type="primary">选择</el-button>
                    </el-upload>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-form>
            <div style="
                display: flex;
                justify-content: center;
                width: 100%;
                margin: 10px 0;
              ">
              <el-button size="mini" type="primary" @click="getTestlink('formover')">获取测试链接</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="驱动名称：" prop="driver_name" v-if="collectTypeValue !== 'Mongodb'">
          <el-input v-model="sourceForm.driver_name" readonly maxlength="50" placeholder="请先填写基本信息">
            <!-- <el-button slot="append" icon="el-icon-edit"></el-button> -->
          </el-input>
        </el-form-item>
        <el-form-item label="源地址：" prop="url">
          <el-input v-model="sourceForm.url" maxlength="300" readonly placeholder="请先填写基本信息"></el-input>
        </el-form-item>
        <!-- <el-form-item label="源账号：" prop="username">
          <el-input v-model="sourceForm.username" maxlength="30" placeholder="请输入源账号"></el-input>
        </el-form-item>
        <el-form-item label="源密码：" prop="password">
          <el-input v-model="sourceForm.password" type="password" maxlength="30" placeholder="请输入源密码"></el-input>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sourceForm.visible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
  import {
    SOURCEDATABASE
  } from "../../common/database";
  export default {
    name: "index",
    data: function () {
      return {
        paginations: {
          pageIndex: 1, // 当前位于哪页
          pageSize: 20, // 页显示多少条
          total: 0, // 总数
          layout: "total, prev, pager, next", // 翻页属性
        },
        tableData: [],
        sourceForm: {
          visible: false,
          title: '添加',
          rules: {
            name: [{
              required: true,
              message: "名称不能为空"
            }],
            type: [{
              required: true,
              message: "源类型不能为空"
            }],
            driver_name: [{
              required: true,
              message: "驱动名称不能为空"
            }],
            url: [{
              required: true,
              message: "源地址不能为空"
            }],
            username: [{
              required: true,
              message: "源账号不能为空"
            }],
            password: [{
              required: true,
              message: "源密码不能为空"
            }],
          },
          id: 0,
          name: "",
          type: "",
          driver_name: "",
          url: "",
          username: "",
          password: "",
          dbFilepath: "",
          table_name: ''
        },
        sourceDataType: SOURCEDATABASE, //数据源类型数组
        /* base start*/
        collectTypeValue: "", //数据源类型
        collectBaseInfo: {
          version: "1"
        },
        fileList: [],
        fileListone: [],

        //正则预览返回
        regexdata: [],
        available: "", //文件 上传需要的格式

        // //规则
        infoRule: {
          ip: [{
              required: true,
              message: "请输入ip",
              trigger: "blur"
            },
            {
              validator: (rule, value, callback) => {
                // 修改IP 匹配的正则表达式
                var reg =
                  /^([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/;
                if (reg.test(value)) {
                  callback();
                } else {
                  callback(new Error("请输入正确的ip"));
                }
              },
              trigger: "blur",
            },
          ],
          port: [{
              required: true,
              message: "请输入端口号",
              trigger: "blur"
            },
            {
              validator: (rule, value, callback) => {
                if (value <= 65535 && value >= 0) {
                  callback();
                } else {
                  callback(new Error("请输入正确的端口号"));
                }
              },
              trigger: "blur",
            },
          ],
          serviceName: [{
            required: true,
            message: "请输入服务名",
            trigger: "blur"
          }, ],
          username: [{
            required: true,
            message: "请输入用户名",
            trigger: "blur"
          }, ],
          password: [{
            required: true,
            message: "请输入密码",
            trigger: "blur"
          }],
          domains: [{
              required: true,
              message: "请输入域名",
              trigger: "blur"
            },
            {
              validator: (rule, value, callback) => {
                var reg =
                  /^(?=^.{3,255}$)(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\d+)*(\/\w+\.\w+)*([\?&]\w+=\w*)*$/;
                if (reg.test(value)) {
                  callback();
                } else {
                  callback(new Error("请输入正确的URL"));
                }
              },
              trigger: "blur",
            },
          ],
        },
        /* base end*/
      };
    },
    methods: {
      jump(i) {
        if (i === undefined) {
          i = this.paginations.pageIndex;
        } else {
          this.paginations.pageIndex = i;
        }
        this.$store.dispatch("ajaxSetting", {
          //   this.$store.dispatch("ajax", {//old
          url: "/api/dataSource/queryDataSourceList",
          method: "get",
          data: {
            page: i,
            number: this.paginations.pageSize
          },
          succeed: (res) => {
            this.tableData = res.rows;
            this.paginations.total = res.total;
          },
        });
      },
      //添加数据源
      add() {
        this.initBaseInfo();
        this.sourceForm.visible = true;
        setTimeout(() => {
          this.$refs['sourceForm'].resetFields();
          this.sourceForm.title = "添加";
          this.sourceForm.id = 0;
          this.sourceForm.name = "";
          this.collectTypeValue = this.sourceDataType[0].value;
          this.sourceForm.type = this.sourceDataType[0].value;
          this.sourceForm.driver_name = "";
          this.sourceForm.url = "";
          this.sourceForm.username = "";
          this.sourceForm.password = "";
          this.sourceForm.rules.password[0].required = true;
        }, 500);


      },
      //账号赋值
      assignmentUser(val) {
        this.sourceForm.username = val
      },
      //密码赋值
    //   assignmentPass(val) {
    //     this.sourceForm.password = val
    //   },
      //编辑数据源
      edit(row) {
        console.log(row);
        this.sourceForm.visible = true;
        this.sourceForm.title = "编辑";
        this.collectTypeValue = row.type;
        this.sourceForm.id = row.id;
        this.sourceForm.name = row.name;
        this.sourceForm.type = row.type;
        this.sourceForm.driver_name = row.driver_name;
        this.sourceForm.url = row.url;
        this.sourceForm.username = row.username;
        this.sourceForm.password = row.password;
        this.collectBaseInfo.username = row.username;
         this.$set(this.collectBaseInfo, "password",  row.password);
        this.sourceForm.rules.password[0].required = false;
         console.log(this.collectTypeValue);
         this.$forceUpdate();
      },
      save() {
        this.$refs.sourceForm.validate((valid) => {
          if (valid) {
            if (this.sourceForm.id === 0) {
              this.$store.dispatch("ajaxSetting", {
                // this.$store.dispatch("ajax", {
                url: "/api/dataSource/saveDataSource",
                method: "post",
                data: this.sourceForm,
                succeed: () => {
                  this.jump();
                  this.$message.success("保存成功");
                  this.sourceForm.visible = false;
                  this.$refs.sourceForm.resetFields();
                },
              });
            } else {
              this.$store.dispatch("ajaxSetting", {
                // this.$store.dispatch("ajax", {
                url: "/api/dataSource/saveDataSource",
                method: "post",
                data: this.sourceForm,
                succeed: () => {
                  this.jump();
                  this.$message.success("保存成功");
                  this.sourceForm.visible = false;
                  this.$refs.sourceForm.resetFields();
                },
              });
            }
          }
        });
      },
      del(row) {
        this.delPopoverClose("del_popover_" + row.id);
        this.$store.dispatch("ajaxSetting", {
          //   this.$store.dispatch("ajax", {
          url: "/api/dataSource/deleteDataSource",
          // url: "api/dataSource/deleteDataSource",
          method: "put",
          data: {
            ids: [row.id]
          },
          succeed: () => {
            this.jump();
            this.$message.success("删除成功");
            this.delPopoverClose("del_popover_" + row.id);
          },
        });
      },
      /* 基本信息 start */
      //初始化
      initBaseInfo() {
        this.collectTypeValue = this.sourceDataType[0].value;
        this.sourceForm.type = this.sourceDataType[0].value;
        this.exchangeType(this.collectTypeValue);
      },
      //切换数据源类型
      exchangeType(val) {
        console.log(val);
        this.collectTypeValue = val;
        this.collectBaseInfo = {};
        this.currentCheckedType = "";
        this.fileList = []; //清空选择文件
        if (this.sourceForm.visible) {
          this.$refs.formover.resetFields();
        }
        if (val == "access") {
          // console.log("-----选中access的时候");
          this.available = ".mdb,.accdb";
        } else if (val == 'sqlite' || val == 'SQLite') {
          this.available = ".db";
        }
        //判断选择oracle数据库
        if (val === "oracle") {
          this.$set(this.collectBaseInfo, "port", 1521);
          this.$set(this.collectBaseInfo, "serviceName", "");
          this.$set(this.collectBaseInfo, "serviceType", "");
          this.$set(this.collectBaseInfo, "ip", "");
        } else if (val === "sqlserver") {
          this.$set(this.collectBaseInfo, "initial", "");
          this.$set(this.collectBaseInfo, "dameng", "");
        }
        if (val === "dm") {
          this.$set(this.collectBaseInfo, "ip", "");
          this.$set(this.collectBaseInfo, "port", "5236");
          this.$set(this.collectBaseInfo, "dameng", "");
        } else if (val === "kingbase") {
          this.$set(this.collectBaseInfo, "serviceName", "");
          this.$set(this.collectBaseInfo, "port", 54321);
        } else if (val === "mysql") {
          this.$set(this.collectBaseInfo, "port", 3306);
          this.$set(this.collectBaseInfo, "ip", "");
          this.$set(this.collectBaseInfo, "dataBaseName", "");
          this.$set(this.collectBaseInfo, "username", "");
          this.$set(this.collectBaseInfo, "password", "");
        } else if (val === "oscar") {
          this.$set(this.collectBaseInfo, "port", 2003);
        }
        this.$forceUpdate();
      },
      //参数配置
      setParams() {
        let obj = {};
        obj["type"] = this.sourceForm.type;
        obj['host'] = this.collectBaseInfo.ip;
        obj['port'] = this.collectBaseInfo.port;
        obj['user'] = this.collectBaseInfo.username;
        obj['password'] = this.collectBaseInfo.password;
        obj['dbName'] = this.collectBaseInfo.dataBaseName;
        // obj['schemaName'] = this.collectBaseInfo.password;
        obj['table_name'] = this.collectBaseInfo.table_name;
        obj['dbFilepath'] = this.collectBaseInfo.dbFilepath;
        return obj;
      },
      //测试连接
      getTestlink(ref) {
        let _this = this;
        this.$refs[ref].validate((valid) => {
          if (valid) {
            let params = _this.setParams();
            _this.$store.dispatch("ajaxSetting", {
              url: "/zonghe/api/database/databaseConnection",
              method: "post",
              data: params,
              succeed: (res) => {
                // console.log(res);
                if (res.code == 200) {
                  this.$message.success(res.data)
                  this.sourceForm.driver_name = res.driverClassName;
                  this.sourceForm.url = res.url;
                }
              },
            });
          }
        });
      },
      //上传事件
      handleChange(file, fileList) {
        this.fileList = fileList;
        this.$refs.uploadAcc.submit();
      },
      changeheader() {
        for (let i = 0; i < this.fileList.length; i++) {
          let pic = new FormData();
          pic.append("file", this.fileList[i].raw);
          // console.log(pic);
          this.$store.dispatch("ajax", {
            url: `/zonghe/api/upload_file/_file`,
            // url: `/zonghe/api/uploadfile/_file`,
            method: "post",
            data: pic,
            succeed: (res) => {
              console.log(res);
              if (res.result == "ok") {
                if (i == this.fileList.length - 1) {
                  this.$message({
                    type: "success",
                    message: "添加成功!",
                  });
                  this.collectBaseInfo.dbFilepath = res.file.filepath_server;
                  // this.fileList = [];
                  // this.$refs.upload.clearFiles();
                }
              }
            },
          });
        }
      },
      /* 基本信息 end */
      delPopoverShow(ref) {
        this.$refs[ref].doShow();
      },
      delPopoverClose(ref) {
        this.$refs[ref].doClose();
      },
    },
    mounted: function () {
      this.jump(1);
    },
  };
</script>